const API = require('../../utils/api')
Page({
  data: {
    userInfo:{},
    defaultAvatar:'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
    loginFlg:false,
    stats: {
      courtBookings: 0,
      coachBookings: 0,
      points: 0
    },
    pendingOrders: 0
  },

  async onLoad() {
    if(wx.getStorageSync('token')){
      let userInfoData = await API.userInfo();
      this.setData({
        loginFlg:true,
        userInfo:userInfoData
      })
      const app = getApp();
      app.globalData.userInfo = userInfoData;
    }
  },
  async onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 4
      })
    }
  },

  toLogin(){
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  editAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        try {
          wx.showLoading({ title: '上传中...' })
          const uploadRes = await this.uploadImage(res.tempFilePaths[0])
          const avatarUrl = uploadRes.data.url
          // 更新用户头像
          await getApp().request({
            url: '/user/update-avatar',
            method: 'POST',
            data: { avatar: avatarUrl }
          })
          // 更新本地数据
          const userInfo = { ...this.data.userInfo, avatar: avatarUrl }
          this.setData({ userInfo })
          getApp().globalData.userInfo = userInfo
          wx.setStorageSync('userInfo', userInfo)

          wx.showToast({
            title: '头像更新成功',
            icon: 'success'
          })
        } catch (error) {
          wx.showToast({
            title: '头像更新失败',
            icon: 'none'
          })
        } finally {
          wx.hideLoading()
        }
      }
    })
  },

  uploadImage(filePath) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${getApp().globalData.apiBase}/upload/image`,
        filePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: resolve,
        fail: reject
      })
    })
  },

  editProfile() {
    wx.navigateTo({
      url: '/pages/profile/edit-profile'
    })
  },
  gotoCart(){
    wx.navigateTo({
      url: '/pages/cart/cart',
    })
  },

  gotoCourtBooking(){
    console.log('============')
    wx.navigateTo({
      url: '/pages/courts-booking-list/courts-booking-list',
    })
  },
  gotoCoachBooking(){
    console.log('============')
    wx.navigateTo({
      url: '/pages/coach-booking-list/coach-booking-list',
    })
  },
  goToAddress() {
    wx.navigateTo({
      url: '/pages/profile/address-list'
    })
  },

  goToOrders() {
    wx.navigateTo({
      url: '/pages/orders/orders'
    })
  },

  goToBookings() {
    wx.navigateTo({
      url: '/pages/booking/my-bookings'
    })
  },

  goToFavorites() {
    wx.navigateTo({
      url: '/pages/article-collection/article-collection'
    })
  },

  goToHistory() {
    wx.navigateTo({
      url: '/pages/profile/history'
    })
  },

  userEdit(){
    wx.navigateTo({
      url: '/pages/user-edit/user-edit'
    })
  },
  goArticleList(){
    wx.navigateTo({
      url: '/pages/article-my/article-my'
    })
  },

  handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token')
          const app = getApp();
          app.globalData.userInfo = null;
          this.setData({
            userInfo:{},
            loginFlg:false
          })
        }
      }
    })
  }
})